//
//  SceneKit+Extensions.swift
//  ARDEMO_1
//
//  Created by 37Design on 2021/5/6.
//
import SceneKit
import Foundation
extension SCNNode {
    
    func fit(to node: SCNNode, with offset: Float = 1.5, and rotation: SCNVector4=SCNVector4(), completion: (() -> Void)?=nil) {
        guard let camera = self.camera else { return }
        
        let baseNode = node.clone()
        baseNode.childNode(withName: "shadow_floor", recursively: true)?.removeFromParentNode()
        
        let minCorner = baseNode.boundingBox.min
        let maxCorner = baseNode.boundingBox.max
        let xLength = maxCorner.x - minCorner.x
        let yLength = maxCorner.y - minCorner.y
        let zLength = maxCorner.z - minCorner.z
        
        
        let maxDim = max(max(xLength, yLength), zLength)
        
        
        let fov = Float(camera.fieldOfView) * .pi / 360
        var cameraZ = abs(maxDim / (2 * atan(fov)))
        cameraZ *= offset
        
        let minZ = minCorner.z
        let cameraToFarEdge = (minZ < 0) ? -minZ + cameraZ : cameraZ - minZ
        camera.zFar = Double(cameraToFarEdge * 3)
        
        var newPos = SIMD3<Float>((maxCorner.x + minCorner.x) / 2, (maxCorner.y + minCorner.y) / 2, cameraZ)
        var center = SIMD3((maxCorner.x + minCorner.x) / 2, (maxCorner.y + minCorner.y) / 2, (maxCorner.z + minCorner.z) / 2)
        
        let rotationNode = SCNNode()
        rotationNode.rotation = rotation
        newPos = rotationNode.simdConvertPosition(newPos, to: nil)
        newPos = node.simdConvertPosition(newPos, to: nil)
        
        center = rotationNode.simdConvertPosition(center, to: nil)
        center = node.simdConvertPosition(center, to: nil)
        
        SCNTransaction.begin()
        SCNTransaction.animationDuration = 0.0
        SCNTransaction.completionBlock = completion
        self.simdTransform = simd_float4x4(diagonal: SIMD4<Float>(repeating: 1))
        self.simdPosition = newPos
        self.simdLook(at: center)
        SCNTransaction.commit()
    }
    
    func setHighlighted() {
        categoryBitMask = 2
        for child in self.childNodes {
            child.setHighlighted()
        }
    }
    
    func setUnhighlighted() {
        categoryBitMask = 1
        for child in self.childNodes {
            child.setUnhighlighted()
        }
    }
    
}
